import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Icon, Input, Button, message, Select, InputNumber, Row, Col, DatePicker, TimePicker } from 'antd'
const Option = Select.Option;
const { TextArea } = Input;
const FormItem = Form.Item;
const { MonthPicker } = DatePicker;
import constants from 'share/constants'
import 'styles/expense-reimbursement-control/expense-standard/new-expense-rule.scss'
import Searcher from 'components/searcher'
import searcherDataLib from 'share/searcherData'
import moment from 'moment'
import expenseStandardService from 'containers/expense-reimbursement-control/expense-standard/expense-standard.service'

class NewExpenseRule extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      nowData: {},
      nowPullData: {},
      searcherValue: [],
      formulas: [{
        text: messages('setting.key1529')/*字段*/, value: 1
      },{
        text: messages('common.date')/*日期*/, value: 0
      }]
    };
  }

  onCancel = () => {
    this.props.close();
  };

  getMessageKeyContent = messageKey => {
    let { pullData } = this.props.params;
    let result = messageKey;
    pullData.map(item => {
      if(item.messageKey === messageKey){
        result = item.name;
      }
    });
    return result;
  };

  handleSave = (e) => {
    let { nowData, nowPullData } = this.state;
    let { expenseType, nowRule } = this.props.params;
    if(!nowPullData.ruleDataType){
      message.error(messages('setting.key1640')/*请选择配置项*/);
      return;
    }
    let targetData = JSON.parse(JSON.stringify(nowData));
    if(!targetData.restriction){
      message.error(messages('setting.key1641')/*请选择取值方式*/);
      return;
    }
    if((!targetData.ruleContent || (targetData.ruleContent instanceof Array && targetData.ruleContent.length === 0)) &&
      targetData.ruleContent !== 0 &&
      ['DATETIME', 'DATE', 'MONTH'].indexOf(nowPullData.ruleDataType) === -1 &&
      [1009, 1010].indexOf(targetData.restriction) === -1
    ){
      message.error(messages('setting.key1642')/*条件不能为空*/);
      return;
    }

    if(['DOUBLE', 'LONG', 'POSITIVE_INTEGER'].indexOf(nowPullData.ruleDataType) > -1){
      if(targetData.rightOperatorItem){
        targetData.rightOperatorItem.map(item => {
          targetData.ruleContent += (item.sign + this.getMessageKeyContent(item.messageKey))
        });
        delete targetData.rightOperatorItem;
      }
      if(!isNaN(targetData.ruleContent)){
        targetData.ruleContent = Number(targetData.ruleContent);
      }
    }
    if(targetData.ruleContent){
      if(nowPullData.ruleDataType === 'STRING' && nowPullData.dataSource){
        targetData.ruleContent = targetData.ruleContent.map(item => item.value).join(',')
      }
      if(nowPullData.ruleDataType === 'COST_DEPARTMENT'){
        targetData.ruleContent = targetData.ruleContent.map(item => item.departmentOID).join(',')
      }
      if(nowPullData.ruleDataType === 'COST_CENTER'){
        targetData.ruleContent = targetData.ruleContent.map(item => item.id).join(',')
      }
      if(nowPullData.ruleDataType === 'USER_GROUP'){
        targetData.ruleContent = targetData.ruleContent.map(item => item.id).join(',')
      }
      if(nowPullData.ruleDataType === 'LOCATION_COUNTRY'){
        targetData.ruleContent = targetData.ruleContent.map(item => item.code).join(',')
      }
      if(nowPullData.ruleDataType === 'LOCATION_GROUP'){
        targetData.ruleContent = targetData.ruleContent.map(item => item.id).join(',')
      }
    }
    if(nowPullData.ruleDataType === 'DATETIME'){
      targetData.ruleContent = moment(targetData.ruleContent).utc().format('YYYY-MM-DDTHH:mm:ss') + '.000Z'
    }
    if(nowPullData.ruleDataType === 'DATE'){
      if(!/\+|-/.test(targetData.ruleContent))
        targetData.ruleContent = moment(targetData.ruleContent).format('YYYY-MM-DD');
      else{
        let targetSymbol = targetData.ruleContent.indexOf('+') > -1 ? '+' : '-';
        let sections = targetData.ruleContent.split(targetSymbol);
        if(sections.length < 2 || sections[0] === '' || sections[1] === ''){
          message.error('条件填写不完整');
          return;
        }
      }
    }
    if(nowPullData.ruleDataType === 'MONTH'){
      targetData.ruleContent = moment(targetData.ruleContent).format('YYYY-MM');
    }
    targetData.ruleDataType = nowPullData.ruleDataType;
    targetData.leftFieldType = nowPullData.fieldType;
    targetData.dataSource = nowPullData.dataSource;
    targetData.enabled = true;
    targetData.configId = nowRule.id;
    targetData.leftSource = "INVOICE";
    this.setState({ loading: true });
    expenseStandardService.saveCondition(expenseType.expenseTypeOID, targetData).then(res => {
      this.setState({ loading: false });
      message.success(messages('setting.key211')/*保存成功*/);
      this.props.close(true);
    }).catch(e => {
      if (e.response.data) {
        message.error(e.response.data.validationErrors ? e.response.data.validationErrors[0].message : e.response.data.message);
      }
      this.setState({ loading: false });
    })
  };

  componentWillReceiveProps(nextProps){
    const { showSlideFrame, nowCondition, pullData, searcherValue } = nextProps;
    if(showSlideFrame !== this.props.showSlideFrame){
      if(showSlideFrame){
        if(nowCondition.id){
          let targetNowData = JSON.parse(JSON.stringify(nowCondition));
          let nowPullData = {};
          pullData.map(item => {
            if(item.messageKey === targetNowData.messageKey){
              nowPullData = item;
            }
          });
          if(['DOUBLE', 'LONG', 'POSITIVE_INTEGER'].indexOf(nowPullData.fieldType) > -1){
            //给一个结束符
            targetNowData.ruleContent = targetNowData.ruleContent ? targetNowData.ruleContent + '$' : undefined;
            let sections = targetNowData.ruleContent ? targetNowData.ruleContent.split('') : [];
            let word = '';
            targetNowData.rightOperatorItem = [];
            //是否已经拿到第一个数字
            let getRuleContent = false;
            let lastChar = null;
            sections.map(char => {
              if(['+', '-', '*', '/', '$'].indexOf(char) > -1){
                if(getRuleContent){
                  if(lastChar){
                    targetNowData.rightOperatorItem.push({
                      sign: lastChar,
                      messageKey: word
                    });
                  }
                } else {
                  targetNowData.ruleContent = Number(word);
                  getRuleContent = true;
                }
                lastChar = char;
                word = '';
              } else {
                word += char;
              }
            });
            let count = 0;
            let rightFields = targetNowData.rightFieldName;
            if(rightFields){
              rightFields = rightFields.replace(/\s+/g,"");
              rightFields = rightFields.split(',');
              targetNowData.rightOperatorItem.map(item => {
                if(isNaN(item.messageKey)){
                  item.messageKey = rightFields[count];
                  count++;
                }
              });
            }
          }
          this.setState({
            nowData: targetNowData,
            nowPullData,
            searcherValue
          })
        } else {
          this.setState({
            nowData: {},
            nowPullData: {},
            searcherValue: []
          })
        }
      } else {
        this.setState({
          nowData: {},
          nowPullData: {},
          searcherValue: []
        })
      }
    }
  }

  handleChangeMessageKey = messageKey => {
    let { nowData } = this.state;
    let { pullData } = this.props;
    nowData.messageKey = messageKey;
    nowData.restriction = null;
    let nowPullData = {};
    pullData.map(item => {
      if(item.messageKey === nowData.messageKey){
        nowPullData = item;
      }
    });
    nowData.ruleContent = null;
    if(['DATETIME', 'DATE', 'MONTH'].indexOf(nowPullData.fieldType) > -1){
      nowData.ruleContent = undefined;
    }
    if(['DOUBLE', 'LONG', 'POSITIVE_INTEGER'].indexOf(nowPullData.fieldType) > -1){
      nowData.rightOperatorItem = [];
    }
    this.setState({
      nowData,
      nowPullData
    });
  };

  handleChangeNowDataAttr = (value, attr) => {
    let { nowData, nowPullData } = this.state;
    nowData[attr] = value;
    if(attr === 'restriction' && [1009, 1010].indexOf(value) > -1){
      nowData.ruleContent = null;
      if(['DATETIME', 'DATE', 'MONTH'].indexOf(nowPullData.fieldType) > -1){
        nowData.ruleContent = undefined;
      }
    }
    this.setState({ nowData })
  };

  handleChangeOperator = (index, attr, value) => {
    let { nowData } = this.state;
    nowData.rightOperatorItem[index][attr] = value;
    this.setState({ nowData });
  };

  handleAddOperator = () => {
    let { nowData } = this.state;
    nowData.rightOperatorItem.push({
      sign: null,
      messageKey: ''
    });
    this.setState({ nowData });
  };

  handleDeleteOperator = index => {
    let { nowData } = this.state;
    nowData.rightOperatorItem.splice(index, 1);
    this.setState({ nowData });
  };

  renderDoubleForm = long => {
    let { nowData } = this.state;
    const { pullData } = this.props.params;
    let longProps = long ? {
      precision: 0
    } : {};
    return (
      <div>
        <InputNumber style={{ width: '100%' }}
                     value={nowData.ruleContent}
                     min={0}
                     onChange={ruleContent => this.handleChangeNowDataAttr(ruleContent, 'ruleContent')}
                     {...longProps}/>
        {nowData.rightOperatorItem.map((operator, index) => (
          <Row gutter={20} style={{ marginTop: 20, position: 'relative' }} key={index}>
            <Col span={10}>
              <Select value={operator.sign}
                      onChange={value => this.handleChangeOperator(index, 'sign', value)}>
                {['+', '-', '*', '/'].map(item => <Option value={item} key={item}>{item}</Option>)}
              </Select>
            </Col>
            <Col span={14}>
              <Select
                filterOption={(inputValue, option) => option.props.children.indexOf(inputValue) > -1}
                mode="combobox"
                optionLabelProp="children"
                value={operator.messageKey}
                onChange={value => this.handleChangeOperator(index, 'messageKey', value)}
              >
                {pullData.filter(item => ['DOUBLE', 'LONG', 'POSITIVE_INTEGER'].indexOf(item.fieldType) > -1).map(item => <Option key={item.messageKey} value={item.messageKey}>{item.name}</Option>)}
              </Select>
            </Col>
            <Icon onClick={() => this.handleDeleteOperator(index)} type="minus-circle" className="delete-operator-item"/>
          </Row>
        ))}
        <div className="new-operator-item" onClick={this.handleAddOperator}> {messages('setting.key1207')/*添加条件*/}&nbsp;<Icon type="plus" />
        </div>
      </div>
    )
  };

  renderTextForm = () => {
    let { nowData, nowPullData } = this.state;
    let { language ,tenantMode } = this.props;
    let searcherData = {};
    switch(nowPullData.ruleDataType){
      case 'STRING':
        if(nowPullData.dataSource){
          let searcherItem = JSON.parse(JSON.stringify(searcherDataLib['enumerations']));
          searcherItem.url = searcherItem.url.replace('{enumerationOID}', nowPullData.dataSource);
          searcherData = {
            searcherItem,
            type: '',
            params: { page: 0, size: 1000 },
            labelKey: "messageKey"
          };
          break;
        } else {
          return (
            <div>
              <TextArea value={nowData.ruleContent}
                        autosize={{minRows: 6, maxRows: 6}}
                        onChange={e => this.handleChangeNowDataAttr(e.target.value, 'ruleContent')}
                        maxLength="1995"/>
            </div>
          );
        }
      case 'COST_DEPARTMENT':
        searcherData = {
          type: 'all_department',
          params: { flag: 1002, hasChildren: false, name: '' },
          labelKey: "path"
        };
        break;
      case 'COST_CENTER':
        let searcherItem = JSON.parse(JSON.stringify(searcherDataLib['cost_center_item']));
        searcherItem.url = searcherItem.url.replace('{costCenterOID}', nowData.messageKey);
        searcherData = {
          searcherItem,
          type: 'costCenterItem',
          params: { page: 0, size: 1000 },
          labelKey: "name"
        };
        break;
      case 'USER_GROUP':
        searcherData = {
          type: 'user_group',
          params: { page: 0, size: 1000, enabled: true },
          labelKey: "name"
        };
        tenantMode && (searcherData.type = 'user_group_book');
        break;
      case 'LOCATION_COUNTRY':
        searcherData = {
          type: 'country',
          params: {language: language.code, type: 'country'},
          labelKey: 'country'
        };
        break;
      case 'LOCATION_GROUP':
        searcherData = {
          type: 'city_level',
          params: {deleted: false, page: 0, size: 1000},
          labelKey: 'levelName'
        };
        break;
    }
    return <Searcher type={searcherData.type}
                     searcherItem={searcherData.searcherItem}
                     listExtraParams={searcherData.params}
                     labelKey={searcherData.labelKey}
                     value={nowData.ruleContent}
                     newline
                     onChange={value => this.handleChangeNowDataAttr(value, 'ruleContent')}/>
  };

  handleChangeDateRightFieldName = (value, formulaData) => {
    let { nowData } = this.state;
    let { pullData } = this.props;
    nowData.rightFieldName = value;
    let contents = nowData.ruleContent.split(formulaData.sign);
    contents[0] = pullData.find(item => item.messageKey === value).name;
    nowData.ruleContent = contents.join(formulaData.sign);
    this.setState({ nowData });
  };

  handleChangeFormula = formula => {
    let { nowData } = this.state;
    nowData.formula = Boolean(formula);
    console.log(formula);
    if(formula){
      nowData.rightFieldName = null;
      nowData.ruleContent = "+";
    } else {
      nowData.ruleContent = new Date().format('yyyy-MM-dd');
    }
    this.setState({ nowData });
  };

  handleChangeFormulaSign = (sign, formulaData) => {
    let { nowData } = this.state;
    nowData.ruleContent = nowData.ruleContent.replace(formulaData.sign, sign);
    this.setState({ nowData });
  };

  onChangeFormulaData = (value, formulaData) => {
    let { nowData } = this.state;
    if(!value && value !== 0) value = '';
    nowData.ruleContent = nowData.ruleContent.replace(/[+|-]\S*/g, `${formulaData.sign}${value}`);
    this.setState({ nowData });
  };

  renderDateForm(){
    let { nowData, formulas } = this.state;
    const { pullData } = this.props.params;
    let formulaData = {};
    if(nowData.formula){
      if(nowData.ruleContent){
        ['+', '-'].map(sign => {
          if(nowData.ruleContent.indexOf(sign) > -1){
            let sections = nowData.ruleContent.split(sign);
            formulaData.sign = sign;
            formulaData.number = sections[1] || '';
          }
        });
      }
    }
    return (
      <div>
        <Select value={nowData.formula ? 1 : 0}
                onChange={this.handleChangeFormula}
                style={{ marginBottom: 24 }}>
          {formulas.map(item => <Option value={item.value} key={item.value}>{item.text}</Option>)}
        </Select>
        {nowData.formula ? (
          <div>
            <Select value={nowData.rightFieldName}
                    style={{ marginBottom: 24 }}
                    onChange={value => this.handleChangeDateRightFieldName(value, formulaData)}>
              {pullData.filter(item => item.fieldType === 'DATE').map(item => <Option key={item.messageKey}>{item.name}</Option>)}
            </Select>
            <Row gutter={20}>
              <Col span={10}>
                <Select value={formulaData.sign} onChange={value => this.handleChangeFormulaSign(value, formulaData)}>
                  {['+', '-'].map(item => <Option value={item} key={item}>{item}</Option>)}
                </Select>
              </Col>
              <Col span={14}>
                <InputNumber style={{ width: '100%' }}
                             value={formulaData.number}
                             onChange={value => this.onChangeFormulaData(value, formulaData)}/>
              </Col>
            </Row>
          </div>
        ) : (
          <DatePicker value={moment(nowData.ruleContent)}
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                      onChange={value => this.handleChangeNowDataAttr(value.format('YYYY-MM-DD'), 'ruleContent')}/>
        )}
      </div>
    )
  }

  renderTimeForm = () => {
    let { nowData } = this.state;
    return (
      <div>
        <TimePicker format="HH:mm"
                    value={moment(nowData.ruleContent)}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                    onChange={value => this.handleChangeNowDataAttr(value.format('YYYY-MM-DDTHH:mm'), 'ruleContent')}/>
      </div>
    )
  };

  renderMonthForm = () => {
    let { nowData } = this.state;
    return (
      <div>
        <MonthPicker format="YYYY-MM"
                     allowClear={false}
                     value={moment(nowData.ruleContent)}
                     getPopupContainer={triggerNode => triggerNode.parentNode}
                     onChange={value => this.handleChangeNowDataAttr(value.format('YYYY-MM'), 'ruleContent')}/>
      </div>
    )
  };

  render(){
    const { nowData, nowPullData } = this.state;
    const { pullData } = this.props.params;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 },
    };
    return (
      <div className="new-expense-rule">
        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label={messages('setting.key1530')/*管控项*/}>
            <Select onChange={this.handleChangeMessageKey} value={nowData.messageKey}>
              {pullData.filter(item => item.ruleDataType !== 'EXPENSE_LEVEL' && item.fieldType !== 'GPS').map(item => <Option key={item.messageKey}>{item.name}</Option>)}
            </Select>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1531')/*取值方式*/}>
            <Select onChange={restriction => this.handleChangeNowDataAttr(restriction, 'restriction')} value={nowData.restriction}>
              {
                constants.restrictions
                  .filter(item => nowPullData.restrictions && nowPullData.restrictions.indexOf(item.value) > -1)
                  .map(item => <Option key={item.value} value={item.value}>{item.text}</Option>)
              }
            </Select>
          </FormItem>
          {[1009, 1010].indexOf(nowData.restriction) === -1 && (
            <FormItem {...formItemLayout} label={messages('setting.key1330')/*条件*/}>
              {nowPullData.fieldType === 'TEXT' && this.renderTextForm()}
              {nowPullData.fieldType === 'CUSTOM_ENUMERATION' && this.renderTextForm()}
              {nowPullData.fieldType === 'LOCATION' && this.renderTextForm()}
              {nowPullData.fieldType === 'DOUBLE' && this.renderDoubleForm()}
              {nowPullData.fieldType === 'LONG' && this.renderDoubleForm(true)}
              {nowPullData.fieldType === 'POSITIVE_INTEGER' && this.renderDoubleForm(true)}
              {nowPullData.fieldType === 'DATE' && this.renderDateForm()}
              {nowPullData.fieldType === 'DATETIME' && this.renderTimeForm()}
              {nowPullData.fieldType === 'MONTH' && this.renderMonthForm()}
            </FormItem>
          )}
          <div className="slide-footer">
            <Button type="primary" loading={this.state.loading} onClick={this.handleSave}>{messages('common.save')/* 保存 */}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')/* 取消 */}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    user: state.login.user,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(NewExpenseRule);

